
import { NMessageProvider, NConfigProvider, NDialogProvider, NModal, NButton, NCard, zhCN, dateZhCN } from 'naive-ui';
import { styled } from '@styils/vue';
import { loadPlugins } from './loadPlugins';

// 定义接口
interface FormProps {
    [key: string]: any
}

// modal的一些扩展属性
interface DialogModalProps extends FormProps {
    onPositiveClick?: (closeDialog:Function,object?:any) => void
    onNegativeClick?: () => void
    // 模态框内联样式
    modalStyle?:object,
    buttonConfirmText:string
    buttonCancelText:string
}

const DIVFlex = styled('div',{
    display:'flex',
    width:'100%',
    height:'100%',
    justifyContent:'center',
    alignItems:'center',
    gap:'20px'
})

// 封装方法
export function showDialog(
    props:FormProps, //表单组件的传参
    modalProps:DialogModalProps, //模态框的传参
    component?:Component //模态框默认插槽传入的组件
):void {
    const show = ref(false); //控制模态框的打开隐藏
    const componentRef = ref(); // 创建 ref 来引用子组件
    const closeDialog = ()=>{
        show.value = false;
    }
    const handleNegetiveClick = ()=>{
        modalProps.onNegativeClick?.();
        closeDialog();
    }
    const handlePositiveClick = ()=>{
        const componentInstance = componentRef.value;
        // const componentProps = componentInstance?.$props;
        modalProps.onPositiveClick?.(closeDialog, componentInstance);
    }
    const app = createApp({
        render:()=>(
            <NConfigProvider locale={zhCN} date-locale={dateZhCN}>
                <NDialogProvider>
                    <NMessageProvider>
                        <NModal
                          style={modalProps?.modalStyle || {}}  
                          {...modalProps}
                          show={show.value}
                        >
                         <NCard
                           title={modalProps.title}
                           borderd={false}
                           size="huge"
                           role="dialog"
                           aria-modal={true}
                           v-slots={{
                            footer:()=>(
                                <DIVFlex>
                                    <NButton onClick={handleNegetiveClick}>{ modalProps.buttonCancelText }</NButton>
                                    <NButton type="primary" onClick={handlePositiveClick}>{ modalProps.buttonConfirmText }</NButton>
                                </DIVFlex>
                            )
                           }}   
                        >
                             {component ? h(component, {...props,ref: componentRef}) : null}
                         </NCard>
                        </NModal>
                    </NMessageProvider>
                </NDialogProvider>
            </NConfigProvider>
        )
    });
    loadPlugins(app);
    const div = document.createElement('div');
    document.body.appendChild(div);
    app.mount(div);
    show.value = true
}